package com.alibaba.citrus.cr.unified.inventory.facade.service;

import cn.hutool.json.JSONUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.result.Result;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crunifiedinventory.materialretry.dto.GetFailListRequest;
import com.epoch.app.crunifiedinventory.materialretry.dto.RetryMaterialRequest;
import com.epoch.app.crunifiedinventory.materialretry.model.MaterialRetry;
import com.epoch.app.crunifiedinventory.materialretry.service.MaterialRetryService;
import com.epoch.app.crunifiedinventory.model.dto.MaterialRetryLoadListRequest;
import com.epoch.app.crunifiedinventory.model.dto.MnSapCommRetryResponse;
import com.epoch.app.crunifiedinventory.model.dto.MnSapIf004RetryRequest;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author Chen.mu
 * @date 2022/3/15
 */
@Service
@Primary
public class MaterialRetryServiceImpl implements MaterialRetryService {
    public static final int MAX_RETRY_TIMES = 5;
    public static final int RETRY_STATUS_FAILED = 0;
    public static final int RETRY_STATUS_SUCCESS = 1;
    private Log log = Log.getLogger(MaterialRetryServiceImpl.class);
    @Resource
    CrUnifiedInventoryService otsUnifiedInventoryService;
    private static final Integer MAX_PAGE_SIZE = 1000;

    @Override
    public Object retryMaterial(RetryMaterialRequest retryMaterialRequest) {
        MaterialRetryLoadListRequest materialRetryLoadListRequest = new MaterialRetryLoadListRequest();
        materialRetryLoadListRequest.setStatus(0);
        materialRetryLoadListRequest.setLimit(MAX_PAGE_SIZE);
        com.alibaba.lattice2.epoch.sdk.model.Result<List<MaterialRetry>> listResult = loadList(materialRetryLoadListRequest);
        int total = listResult.getTotal();
        List<List<MaterialRetry>> listList = Lists.newArrayList();
        if (total > MAX_PAGE_SIZE){
            Integer totalPage = total % MAX_PAGE_SIZE ==0? total /MAX_PAGE_SIZE : total /MAX_PAGE_SIZE + 1;
            //分页循环查询
            for (int i =0 ;i < totalPage ;i++){
                materialRetryLoadListRequest.setStart(i * MAX_PAGE_SIZE);
                materialRetryLoadListRequest.setLimit(MAX_PAGE_SIZE);
                listResult = loadList(materialRetryLoadListRequest);
                if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                    listList.add(listResult.getResult());
                }
            }
        }else {
            if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                listList.add(listResult.getResult());
            }
        }
        //没有重试记录
        if (CollectionUtils.isEmpty(listList)){
            log.info("MaterialRetryServiceImpl_retryMaterial");
            return Result.success(null);
        }
        for (List<MaterialRetry> retryList : listList) {
            if (CollectionUtils.isEmpty(retryList)) {
                log.warn("retryMaterial retryMaterial#getNoFailedList");
                return Result.success(null);
            }
            log.info("retryMaterial retryMaterial#getFailedList count: {}", retryList.size());
            for (MaterialRetry retryRecord : retryList) {
                MnSapIf004RetryRequest request = JSONUtil.toBean(retryRecord.getRequestJson(), MnSapIf004RetryRequest.class);
                MnSapCommRetryResponse response;
                try {
                    response = otsUnifiedInventoryService.externalSyncMaterial(request);
                } catch (Throwable e) {
                    log.error("retryMaterial retryMaterial#failed with exception:", e);
                    retryFailed(retryRecord);
                    continue;
                }
                boolean retrySuccess = false;
                if (Objects.nonNull(response) && response.getData() != null
                        && response.getData().size() > 0
                        && Objects.nonNull(response.getData().get(0).getStatus())) {
                    retrySuccess = response.getData().get(0).getStatus().equalsIgnoreCase("S");
                }
                if (retrySuccess) {
                    retryRecord.setStatus(RETRY_STATUS_SUCCESS);
                    updateFailMaterial(retryRecord);
                } else {
                    log.error("retryMaterial retryMaterial#failed");
                    retryFailed(retryRecord);
                }
            }
        }

//        List<MaterialRetry> retryList = getFailList(new GetFailListRequest()).getResult();
//        if (CollectionUtils.isEmpty(retryList)) {
//            log.warn("retryMaterial retryMaterial#getNoFailedList");
//            return Result.success(null);
//        }
//        log.info("retryMaterial retryMaterial#getFailedList count: {}", retryList.size());
//        for (MaterialRetry retryRecord : retryList) {
//            MnSapIf004RetryRequest request = JSONUtil.toBean(retryRecord.getRequestJson(), MnSapIf004RetryRequest.class);
//            MnSapCommRetryResponse response;
//            try {
//                response = otsUnifiedInventoryService.externalSyncMaterial(request);
//            } catch (Throwable e) {
//                log.error("retryMaterial retryMaterial#failed with exception:", e);
//                retryFailed(retryRecord);
//                continue;
//            }
//            boolean retrySuccess = false;
//            if (Objects.nonNull(response) && response.getData() != null
//                    && response.getData().size() > 0
//                    && Objects.nonNull(response.getData().get(0).getStatus())) {
//                retrySuccess = response.getData().get(0).getStatus().equalsIgnoreCase("S");
//            }
//            if (retrySuccess) {
//                retryRecord.setStatus(RETRY_STATUS_SUCCESS);
//                updateFailMaterial(retryRecord);
//            } else {
//                log.error("retryMaterial retryMaterial#failed");
//                retryFailed(retryRecord);
//            }
//        }

        return Result.success(null);
    }

    private void retryFailed(MaterialRetry tmp) {
        tmp.setStatus(RETRY_STATUS_FAILED);
        tmp.setRetryTimes(tmp.getRetryTimes() + 1);
        updateFailMaterial(tmp);
        //sls中捕获这个异常，并增加钉钉报警
        if (tmp.getRetryTimes() >= MAX_RETRY_TIMES) {
            log.error("retryMaterial#error marterialID: {} retry times:{}", tmp.getOutMaterialCertificateId(), tmp.getRetryTimes());
        }
    }
}
